package com.yellowpage.nsp.service;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Properties;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

import org.apache.commons.net.ftp.FTPClient;
import org.apache.commons.net.ftp.FTPClientConfig;
import org.apache.commons.net.ftp.FTPReply;
import org.apache.log4j.Logger;

import com.yellowpage.white.util.HttpUtil;

import ch.ethz.ssh2.Connection;
import ch.ethz.ssh2.SCPClient;
import ch.ethz.ssh2.Session;

public class NspGetLoggerServiceImpl {

	private final static Properties properties = new Properties();
	// 日志对象
	private final static Logger logger = Logger
			.getLogger(NspGetLoggerServiceImpl.class);

	private static final int buffer = 2048;

	public NspGetLoggerServiceImpl() {
		try {

			properties.load(this.getClass().getClassLoader()
					.getResourceAsStream("constants.properties"));

		} catch (Exception e) {
			e.printStackTrace();
		}

	}

	public static String getNspLogger(String server, String serverLogName,
			String serverLogPwd, String num, String dateTime) {
		String put_linux_dir = properties.getProperty("LOGERSAVURL");
		if (put_linux_dir == null) {
			put_linux_dir = "E:/object";
		}

		logger.info("The app is starting");

		// logger.info("asduauisd" + put_linux_dir);
		/* 创建connection实例 */
		Connection conn = new Connection(server);
		/* Create a session */
		Session session = null;

		try {
			conn.connect();
			boolean isAuthenticated = conn.authenticateWithPassword(
					serverLogName, serverLogPwd);
			if (isAuthenticated == false) {
				throw new IOException("Authentication failed.");
			}

			// session = conn.openSession();
			// session.requestPTY("logger");
			// session.startShell();
			//
			// InputStream stdout = new StreamGobbler(session.getStdout());
			// InputStream stderr = new StreamGobbler(session.getStderr());
			// BufferedReader stdoutReader = new BufferedReader(new
			// InputStreamReader(stdout));
			// BufferedReader stderrReader = new BufferedReader(new
			// InputStreamReader(stderr));
			// PrintWriter out = new PrintWriter(session.getStdin());
			//
			// out.println("ssh 172.17.225.164");
			// // out.println("v4ByYr_qwk");
			// // out.println("cd /data/log4J");
			// // out.println("ls");
			// // out.println("exit");
			// out.close();
			// session.waitForCondition(ChannelCondition.CLOSED|ChannelCondition.EOF
			// | ChannelCondition.EXIT_STATUS,30000);
			// while (true) {
			// String line = stdoutReader.readLine();
			// if (line == null)break;
			// logger.info(line);
			// }
			// // while (true) {
			// // String line = stderrReader.readLine();
			// // if (line == null)break;
			// // logger.info(line);
			// // }
			// logger.info("ExitCode: " + session.getExitStatus());

			/* 压缩文件 */
			session = conn.openSession();
			// session.execCommand("chmod 777 /data/log4J/fatal_"+dateTime+".log");
			session.execCommand("chmod 777 /data/log4J/fatal_" + dateTime
					+ ".log \n zip /data/log4J/" + num + "_" + dateTime
					+ ".log.zip /data/log4J/fatal_" + dateTime + ".log ");

			SCPClient scpClient = conn.createSCPClient();

			Thread.sleep(60000);

			/* 传输文件 */
			scpClient.get("/data/log4J/" + num + "_" + dateTime + ".log.zip",
					put_linux_dir);

			/* 解压文件 */
			String lastFilePath = "E:/object/" + num + "_" + dateTime
					+ ".log.zip";
			unZip(lastFilePath);

			return "E:/object/fatal_" + dateTime + ".log";
		} catch (Exception e) {
			e.printStackTrace();
			e.printStackTrace(System.err);
			return "";
		} finally {
			/* 关闭connection */
			session.close();
			conn.close();
		}
	}

	public static String unZip(String path) {
		String fileName = "";

		int count = -1;
		int index = -1;

		String savepath = "";
		boolean flag = false;

		savepath = path.substring(0, path.lastIndexOf("/")) + "/";

		try {
			BufferedOutputStream bos = null;
			ZipEntry entry = null;
			FileInputStream fis = new FileInputStream(path);
			ZipInputStream zis = new ZipInputStream(
					new BufferedInputStream(fis));

			while ((entry = zis.getNextEntry()) != null) {
				byte data[] = new byte[buffer];

				String temp = entry.getName();

				index = temp.lastIndexOf("/");
				if (index > -1)
					temp = temp.substring(index + 1);
				temp = savepath + temp;

				File f = new File(temp);
				f.createNewFile();

				fileName = temp;

				FileOutputStream fos = new FileOutputStream(f);
				bos = new BufferedOutputStream(fos, buffer);

				while ((count = zis.read(data, 0, buffer)) != -1) {
					bos.write(data, 0, count);
				}

				bos.flush();
				bos.close();
			}

			zis.close();

		} catch (Exception e) {
			e.printStackTrace();
		}

		return fileName;
	}

	/* 根据FTP方式获取数据 */

	public static String getFTPLonger(String host, int port, String userName,
			String passWord, String path, String localPath, String fileName) {

		FTPClient ftpClient = new FTPClient();
		String name = "";
		try {

			ftpClient.connect(host, port);
			boolean b = ftpClient.login(userName, passWord);// userName、passWord分别为FTP服务器的登陆用户名和密码
			// 检测连接是否成功
			int reply = ftpClient.getReplyCode();
			if (!FTPReply.isPositiveCompletion(reply)) {
				ftpClient.disconnect();
				System.err.println("FTP server refused connection.");
				System.exit(1);
			}
			ftpClient.setControlEncoding("GBK");
			FTPClientConfig conf = new FTPClientConfig(FTPClientConfig.SYST_NT);
			conf.setServerLanguageCode("zh");
			SimpleDateFormat df = new SimpleDateFormat("yyyyMMddHHmmss");
			name = df.format(new Date()) + "longer.zip";
			File localFile = new File("/static/data/" + name);

			FileOutputStream is = new FileOutputStream(localFile);

			String serverFileName = path + "/" + fileName;
			// ftpClient.retrieveFile(serverFileName, is);
			if (!ftpClient.retrieveFile(serverFileName, is)) {
				System.out
						.println("-----------------------Fail to download file, "
								+ ftpClient.getReplyString());
			} else {
				System.out
						.println("-----------------------Success to download file.");
			}
			is.close();
			/*
			 * FTPFile[] remoteFiles = ftpClient.listFiles(path); if
			 * (remoteFiles != null) { for (int i = 0; i < remoteFiles.length;
			 * i++) { SimpleDateFormat df = new
			 * SimpleDateFormat("yyyyMMddHHmmss"); String name = i+"_"+
			 * df.format(new Date())+"longer.zip"; System.out.println(name);
			 * //下载 ftpClient.storeFile(name, fos); File localFile = new
			 * File(localPath+File.separator + name); OutputStream is = new
			 * FileOutputStream(localFile); //retrieveFile的第一个参数需要是 ISO-8859-1
			 * 编码,并且必须是完整路径！ String fileName = path + name;
			 * ftpClient.retrieveFile(new
			 * String(fileName.getBytes("GBK"),"ISO-8859-1"), is); is.close(); }
			 * 
			 * }
			 */
			ftpClient.logout();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			// IOUtils.closeQuietly(outSteam);
			try {
				ftpClient.disconnect();
			} catch (IOException ioe) {
				ioe.printStackTrace();
			}
		}
		if (!name.equals("")) {
			// String logerPath=localPath+File.separator+name;
			String logerPath = "/static/data/" + name;

			unZip(logerPath);
			String objFileName = fileName.substring(0, fileName.indexOf("."));
			return localPath + "/fatal_" + objFileName + ".log";
		} else {
			return name;
		}

	}

	public static String getHTTPFile(String path, String url) {
		HttpUtil hu = new HttpUtil();
		try {
			hu.downloadFile(path, url);
			unZip(path);
		} catch (IOException e) {
			e.printStackTrace();
		}

		return path;
	}

}
